﻿using System;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Threading;
using System.Globalization;
using System.Text;
using System.Collections.Generic;

namespace Citi.ConvertTxtToExcel
{
    class Program
    {
        private static readonly string InputFolder = ConfigurationManager.AppSettings["InputFolder"];
        private static readonly string OutputFolder = ConfigurationManager.AppSettings["OutputFolder"];
        private static readonly int RetroactiveDays = int.Parse(ConfigurationManager.AppSettings["RetroactiveDays"]);
        private static readonly int SnoozeMinutes = int.Parse(ConfigurationManager.AppSettings["SnoozeMinutes"]);

        static void Main(string[] args)
        {
            var cultureInfo = new CultureInfo("pt-BR");

            while (true)
            {
                try
                {
                    var filesConverted = new List<string>();

                    var directories = Directory.GetDirectories(OutputFolder);

                    foreach (var directory in directories)
                    {
                        filesConverted.AddRange(Directory.GetFiles(directory).Where(x => File.GetLastWriteTime(x) >= DateTime.Now.AddDays(-RetroactiveDays)
                                      && Path.GetExtension(x) == ".csv")
                                      .Select(x => string.Concat(Path.GetFileNameWithoutExtension(x), ".txt")));
                    }

                    Console.WriteLine("Looking for files to convert");

                    var filesToConvert = Directory.GetFiles(InputFolder).Where(x => !filesConverted.Contains(Path.GetFileName(x))
                        && Path.GetExtension(x) == ".txt"
                        && File.GetLastWriteTime(x) >= DateTime.Now.AddDays(-RetroactiveDays)).ToList();

                    Console.WriteLine("{0} files found.", filesToConvert.Count());

                    foreach (var file in filesToConvert)
                    {
                        var fileName = Path.GetFileNameWithoutExtension(file);
                        var feedFolder = Path.Combine(OutputFolder, fileName.Replace(string.Concat("_", fileName.Split('_').Last()), string.Empty));

                        Console.WriteLine("Converting file {0}", fileName);

                        if (!Directory.Exists(feedFolder))
                            Directory.CreateDirectory(feedFolder);

                        var content = File.ReadAllText(file, Encoding.GetEncoding(cultureInfo.TextInfo.ANSICodePage)).Replace(",", ".").Replace("|", ",");
                        File.WriteAllText(Path.Combine(feedFolder, string.Concat(Path.GetFileNameWithoutExtension(file), ".csv")), content, Encoding.GetEncoding(cultureInfo.TextInfo.ANSICodePage));

                        Console.WriteLine("Converted to {0}", string.Concat(Path.GetFileNameWithoutExtension(file), ".csv"));
                    }
                }
                catch(Exception e)
                {
                    Console.WriteLine("Error: {0}. A new tentative will be done in a few minutes.", e.Message);
                }
                finally
                {
                    Console.WriteLine("Snooze for {0} minutes", SnoozeMinutes);
                    Thread.Sleep(SnoozeMinutes * 60000);
                }
            }
        }
    }
}
